import sys
import os
import logging

import FilenameParser
from Episode import EpisodeInfo
from ShelveFile import Librarian
from Action import MoveFile, DeleteFile
from NearestString import NearestString

extensions = [".avi",".mpg",".divx",".mkv",".wmv"]
stopwords = [ "sample" ]
series_paths = [ '/media/storage/video/series' 
               , '/media/storage/video/series/GordonRamsay'
               ]

class FileInfo(EpisodeInfo):
  path = None
  
  def __repr__(self):
    return '< [%s S%02dE%02d] @ %s>' %( self.series_name
                                      , self.series_number
                                      , self.episode_number
                                      , self.path
                                      )
  def standard_name(self):
    extension = os.path.splitext(os.path.basename(self.path))[1]
    return '%s S%02dE%02d%s' % ( self.series_name
                                , self.series_number
                                , self.episode_number
                                , extension
                                )

def scan(scan_path):
  logger = logging.getLogger('tiger.CollectionScanner.scan')
  logger.info("Scanning %s", scan_path)
  known_series = []
  for path in series_paths:
    p = [    ( s, os.path.join(path,s) ) 
        for  s
        in   os.listdir(path) 
        if   os.path.isdir(os.path.join(path,s)) 
        and  not s.startswith('.')
        ]
    known_series.extend(p)
  logger.debug(known_series)
  series_locations = dict(known_series)
  # Set up a NN classifier for series names
  series_classifier = NearestString(series_locations)

  name_parser = FilenameParser.parser1()
  for dirpath, dirnames, filenames in os.walk(scan_path):
    for filename in filenames:
      root, ext = os.path.splitext(filename)
      if ext.lower() in extensions:
        if all(word not in root for word in stopwords):
	  id_str = dirpath+filename
          episode_info = name_parser(id_str)
          if episode_info:
	    episode_info.series_name = series_classifier(episode_info.series_name)
	    logger.debug('\n    %s --> %s', id_str, episode_info)
            file_info = FileInfo(parent = episode_info)
            file_info.path = os.path.join(dirpath, filename)
            yield file_info
	  else:
	    logger.debug('\n  Parse failed: %s', id_str)

def tidy(librarian, file_info):
  shelf = librarian.find_shelf(file_info)
  filename = file_info.standard_name() 
  target = os.path.join(shelf, filename)
  return MoveFile(file_info.path, target)
           

if __name__ == "__main__":
  if len(sys.argv) == 2:
    path = sys.argv[1]
  else:
    path = '/media/storage/downloads/usenet/TV/'
  print "Library Path:", path
  files = scan(path)
  librarian = Librarian(series_paths)
  actions = [ tidy(librarian, file) for file in files ]
  for action in actions:
    pending_actions = [action]
    while len(pending_actions) > 0:
      action = pending_actions.pop(0)
      print action
      response = raw_input("Execute? (y/n)")
      if response == 'y':
        additional_actions = action.execute()
        if additional_actions is not None:
          pending_actions = additional_actions + pending_actions
      else:
        if isinstance(action, MoveFile):
          pending_actions.insert(0, DeleteFile(action.src))




